<?php

namespace App\Providers;

use App\Helpers\SelfValidationRule;
use App\Models\System\ConfigModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\Finder\Finder;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
        $this->extendValidator();
        $this->registerDbConfig();
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->provides();
        $viewPath = base_path('resources/views/backend/'.config('app.backend_theme').'/');

        $loginPath = base_path('resources/views/backend/login/');
        $this->loadViewsFrom($viewPath,'backend');
        $this->loadViewsFrom($loginPath,'auth');
    }

    public function provides()
    {
        $modules = $this->app['files']->directories(base_path('modules'));
        $providers = [];
        foreach ($modules as $dir){
            if($this->app['files']->exists($dir.DIRECTORY_SEPARATOR.'composer.json')){
                $composer = json_decode($this->app['files']->get($dir.DIRECTORY_SEPARATOR.'composer.json'), true);
                foreach ($composer['provider'] as $provider){
                    $this->app->register($provider);
                }
            }
        }
       return $providers;
    }

    private function registerDbConfig()
    {
        $sys_config = \Cache::rememberForever('website', function() {
            return self::getSysConfig();
        });

        if($sys_config){
            config(['website' => $sys_config]);
        }else{
            Cache::forget('website');
        }
    }

    /**
     * 获取数据库中的配置列表
     * @return array 配置数组
     */
    private static function getSysConfig(){
        if(!Schema::hasTable('sys_config')){
            return null;
        }
        $data   = ConfigModel::where('status',1)->select('name','type','value')->get();
        $config = [];
        if($data->isNotEmpty()){
            foreach ($data as $value) {
                $config[$value->name] = self::configFormat($value->type, $value->value);
            }
        }
        return $config;
    }

    private static function configFormat($type, $value){
        switch ($type) {
            case 3: //解析数组
                $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
                if(strpos($value,':')){
                    $value  = array();
                    foreach ($array as $val) {
                        list($k, $v) = explode(':', $val);
                        $value[$k]   = $v;
                    }
                }else{
                    $value =    $array;
                }
                break;
        }
        return $value;
    }

    /**
     * @title 扩展验证规则
     */
    public function extendValidator()
    {
        Validator::extend('alpha_start',function($attribute, $value, $parameters, $validator){
            return SelfValidationRule::alphaStart($value);
        });

        Validator::extend('pwd_rule',function($attribute, $value, $parameters, $validator){
           return SelfValidationRule::pwdSimpleFormat($value);
        });

        Validator::extend('mobile',function($attribute, $value, $parameters, $validator){
            return SelfValidationRule::mobileFormat($value);
        });

        Validator::extend('text_rule',function($attribute, $value, $parameters, $validator){
            return SelfValidationRule::textSafetyFormat($value);
        });
    }
}
